<!DOCTYPE html>
<html lang="en">

<head>
    <title>Search Results</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="scripts/checklogin.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3b82f6',
                        secondary: '#f97316',
                        neutral: '#f3f4f6',
                        dark: '#1f2937'
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-shadow {
                box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
            }
            .btn-hover {
                @apply transition-all duration-300 hover:shadow-lg hover:-translate-y-1;
            }
            .fade-in {
                animation: fadeIn 0.5s ease-in-out;
            }
            @keyframes fadeIn {
                from {
                    opacity: 0;
                    transform: translateY(10px);
                }
                to {
                    opacity: 1;
                    transform: translateY(0);
                }
            }
        }

        /* 添加背景图片样式 */
        body {
            background-image: url('https://img.shetu66.com/2022/11/04/1667562774577428.jpg');
            background-size: cover;
            background-position: center;
            position: relative;
        }

        body::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.7);
            z-index: -1;
        }

        /* 放大 Back to Search 按钮 */
        .back-to-search {
            font-size: 1.25rem; /* 调整字体大小 */
            padding: 0.75rem 1.5rem; /* 调整内边距 */
        }
    </style>
</head>

<body class="font-inter bg-gray-50 min-h-screen flex flex-col">
    <!-- 导航栏 -->
    <nav class="bg-primary text-white shadow-md">

            <button class="md:hidden text-xl" id="mobile-menu-button">
                <i class="fa fa-bars"></i>
            </button>
        </div>
        <!-- 移动端菜单 -->
        <div class="md:hidden hidden bg-primary/95 backdrop-blur-sm" id="mobile-menu">
            <div class="container mx-auto px-4 py-2 flex flex-col space-y-3">
                <a href="Value.html" class="py-2 hover:text-secondary transition-colors duration-300">Home</a>
                <a href="#" class="py-2 hover:text-secondary transition-colors duration-300">Categories</a>
                <a href="#" class="py-2 hover:text-secondary transition-colors duration-300">About</a>
            </div>
        </div>
    </nav>

    <!-- 返回按钮 -->
    <div class="container mx-auto px-4 py-4">
        <a href="Value.html"
            class="inline-flex items-center text-primary hover:text-primary/80 transition-colors duration-300 back-to-search">
            <i class="fa fa-arrow-left mr-2"></i>
            Back to Search
        </a>
    </div>

    <!-- 搜索结果展示 -->
    <main class="flex-grow container mx-auto px-4 py-6">
        <div id="searchResults" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <!-- 搜索结果将通过 JavaScript 动态添加 -->
        </div>
    </main>

    <script>
        // 移动端菜单切换
        document.getElementById('mobile-menu-button').addEventListener('click', function () {
            const mobileMenu = document.getElementById('mobile-menu');
            mobileMenu.classList.toggle('hidden');
        });

        document.addEventListener('DOMContentLoaded', function () {
            const urlParams = new URLSearchParams(window.location.search);
            const searchTerm = urlParams.get('searchTerm');
            const resultsDiv = document.getElementById('searchResults');

            // 模拟食物数据
            const foods = [
                {
                    id: 1,
                    name: 'Kung Pao Chicken',
                    image: 'images/gongbao.png',
                    description: 'A classic Chinese dish with diced chicken, peanuts, vegetables, and chili peppers.',
                    ingredients: [
                        { name: 'Chicken breast', price: '$5.00', image: 'images/chicken.png' },
                        { name: 'Peanuts', price: '$2.00', image: 'images/peanut.png' },
                        { name: 'Cucumber', price: '$1.00', image: 'images/huanggua.png' },
                        { name: 'Dried chili', price: '$0.50', image: 'images/dry_chili.png' }
                    ]
                },
                {
                    id: 2,
                    name: 'Tomato and Egg Stir-Fry',
                    image: 'images/fanqie.png',
                    description: 'A simple and nutritious Chinese家常菜 made with tomatoes and eggs.',
                    ingredients: [
                        { name: 'Tomato', price: '$2.00', image: 'images/tomato.png' },
                        { name: 'Egg', price: '$3.00', image: 'images/egg.png' },
                        { name: 'White sugar', price: '$0.50', image: 'images/shatang.png' },
                        { name: 'Salt', price: '$0.20', image: 'images/shiyan.png' }
                    ]
                },
                {
                    id: 3,
                    name: 'Beef Stew',
                    image: 'images/beef1.png',
                    description: 'A hearty stew made with tender beef, potatoes, carrots, and onions.',
                    ingredients: [
                        { name: 'Beef', price: '$8.00', image: 'images/beef2.png' },
                        { name: 'Potato', price: '$1.50', image: 'images/beef3.png' },
                        { name: 'Carrot', price: '$1.00', image: 'images/beef4.png' },
                        { name: 'Onion', price: '$0.80', image: 'images/beef5.png' }
                    ]
                }
            ];

            // 加载本地存储中的搜索结果
            loadSearchResults();

            // 搜索结果处理
            if (searchTerm) {
                const matchedFood = foods.find(food =>
                    food.name.toLowerCase().includes(searchTerm.toLowerCase())
                );

                if (matchedFood) {
                    // 创建食物卡片
                    const foodCard = createFoodCard(matchedFood);
                    resultsDiv.appendChild(foodCard);

                    // 保存搜索结果到本地存储
                    saveSearchResult(matchedFood);
                } else {
                    // 没有找到结果
                    const noResultsDiv = document.createElement('div');
                    noResultsDiv.className = 'col-span-full flex flex-col items-center justify-center py-12';
                    noResultsDiv.innerHTML = `
                        <div class="w-24 h-24 bg-gray-200 rounded-full flex items-center justify-center mb-4">
                            <i class="fa fa-search text-gray-400 text-4xl"></i>
                        </div>
                        <h2 class="text-xl font-semibold text-gray-800 mb-2">No results found</h2>
                        <p class="text-gray-600 mb-4">We couldn't find any recipes for "${searchTerm}". Try searching for something else.</p>
                        <a href="Value.html" class="inline-flex items-center px-4 py-2 bg-primary text-white rounded-lg btn-hover">
                            <i class="fa fa-arrow-left mr-2"></i> Back to Search
                        </a>
                    `;
                    resultsDiv.appendChild(noResultsDiv);
                }
            } else {
                // 没有搜索词
                const noSearchTermDiv = document.createElement('div');
                noSearchTermDiv.className = 'col-span-full flex flex-col items-center justify-center py-12';
                noSearchTermDiv.innerHTML = `
                    <div class="w-24 h-24 bg-gray-200 rounded-full flex items-center justify-center mb-4">
                        <i class="fa fa-search text-gray-400 text-4xl"></i>
                    </div>
                    <h2 class="text-xl font-semibold text-gray-800 mb-2">No search term provided</h2>
                    <p class="text-gray-600 mb-4">Please enter a food name to search for recipes.</p>
                    <a href="Value.html" class="inline-flex items-center px-4 py-2 bg-primary text-white rounded-lg btn-hover">
                        <i class="fa fa-arrow-left mr-2"></i> Back to Search
                    </a>
                `;
                resultsDiv.appendChild(noSearchTermDiv);
            }

            // 保存搜索历史
            saveSearchHistory(searchTerm);
        });

        // 创建食物卡片
        function createFoodCard(matchedFood) {
            const foodCard = document.createElement('div');
            foodCard.className = 'bg-white rounded-xl overflow-hidden card-shadow transition-all duration-300 hover:shadow-xl fade-in';
            foodCard.innerHTML = `
                <div class="relative">
                    <img src="${matchedFood.image}" alt="${matchedFood.name}" class="w-full h-64 object-cover">
                    <div class="absolute top-4 left-4 bg-primary/90 text-white px-3 py-1 rounded-full text-sm">
                        ${matchedFood.name}
                    </div>
                </div>
                <div class="p-6">
                    <p class="text-gray-600 mb-4">${matchedFood.description}</p>
                    <button id="viewIngredientsButton" class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-2 px-4 rounded-lg btn-hover">
                        <i class="fa fa-eye mr-2"></i> View ingredient prices
                    </button>
                    <div id="ingredientsContainer" class="mt-4 hidden">
                        <h3 class="text-lg font-semibold mb-3 text-dark">Ingredients</h3>
                        <div id="ingredientsList" class="grid grid-cols-1 md:grid-cols-2 gap-3">
                            <!-- 配料将通过 JavaScript 添加 -->
                        </div>
                    </div>
                </div>
            `;

            // 查看配料按钮事件
            const viewIngredientsButton = foodCard.querySelector('#viewIngredientsButton');
            const ingredientsContainer = foodCard.querySelector('#ingredientsContainer');
            const ingredientsList = foodCard.querySelector('#ingredientsList');

            viewIngredientsButton.addEventListener('click', function () {
                if (ingredientsContainer.classList.contains('hidden')) {
                    // 清空列表
                    ingredientsList.innerHTML = '';

                    // 添加配料
                    matchedFood.ingredients.forEach(ingredient => {
                        const ingredientCard = document.createElement('div');
                        ingredientCard.className = 'bg-neutral rounded-lg p-3 flex items-center space-x-3 transition-all duration-300 hover:bg-gray-200';
                        ingredientCard.innerHTML = `
                            <img src="${ingredient.image}" alt="${ingredient.name}" class="w-20 h-20 rounded-full object-cover"> <!-- 放大图片尺寸 -->
                            <div class="flex-1">
                                <h4 class="font-medium">${ingredient.name}</h4>
                                <p class="text-primary font-semibold">${ingredient.price}</p>
                            </div>
                        `;
                        ingredientsList.appendChild(ingredientCard);
                    });

                    // 显示配料容器并添加动画
                    ingredientsContainer.classList.remove('hidden');
                    ingredientsContainer.classList.add('animate-fadeIn');

                    // 更新按钮文本
                    viewIngredientsButton.innerHTML = '<i class="fa fa-eye-slash mr-2"></i> Hide ingredient prices';
                } else {
                    // 隐藏配料容器
                    ingredientsContainer.classList.add('hidden');

                    // 更新按钮文本
                    viewIngredientsButton.innerHTML = '<i class="fa fa-eye mr-2"></i> View ingredient prices';
                }
            });

            return foodCard;
        }

        // 保存搜索结果到本地存储
        function saveSearchResult(matchedFood) {
            let searchResults = JSON.parse(localStorage.getItem('searchResults') || '[]');
            const existingIndex = searchResults.findIndex(result => result.id === matchedFood.id);
            if (existingIndex === -1) {
                searchResults.push(matchedFood);
                localStorage.setItem('searchResults', JSON.stringify(searchResults));
            }
        }

        // 加载本地存储中的搜索结果
        function loadSearchResults() {
            const searchResults = JSON.parse(localStorage.getItem('searchResults') || '[]');
            const resultsDiv = document.getElementById('searchResults');
            searchResults.forEach(result => {
                const foodCard = createFoodCard(result);
                resultsDiv.appendChild(foodCard);
            });
        }

        // 保存搜索历史到本地存储
        function saveSearchHistory(term) {
            if (!term) return;

            const maxHistoryItems = 5;
            let searchHistory = JSON.parse(localStorage.getItem('searchHistory') || '[]');

            // 检查是否已存在该搜索词
            const index = searchHistory.findIndex(item => item.toLowerCase() === term.toLowerCase());
            if (index !== -1) {
                // 如果存在，将其移到最前面
                searchHistory.splice(index, 1);
            }

            // 添加到最前面
            searchHistory.unshift(term);

            // 限制历史记录数量
            if (searchHistory.length > maxHistoryItems) {
                searchHistory = searchHistory.slice(0, maxHistoryItems);
            }

            // 保存到本地存储
            localStorage.setItem('searchHistory', JSON.stringify(searchHistory));
        }
    </script>
</body>

</html>